﻿using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Framework.Exceptions.RepositoryExceptions;
using Interfaces.Criteria;
using Interfaces.Filters;
using Interfaces.Models;
using Interfaces.Providers;
using Interfaces.Repositories;
using Interfaces.RepositoryModels.InternalModels.EconomicInformationModels;

namespace SQLRepositories.EconomicRepositories
{
    public class XchangeRateRepository : EntityBaseRepository<XchangeRateModel>, IXchangeRateRepository, IEconomicDataProvider<IEnumerable<IXchangeRate>, IXchangeRateFilter, IKeySupportedCriteria>
    {
        public XchangeRateRepository(IDBEconomicInformationServiceContext context) 
            : base(context)
        {}

        public void Create(XchangeRateModel item)
        {
            Context.XchangeRates.Add(item);
            Context.SaveChanges();
        }

        public XchangeRateModel GetById(Guid id)
        {
            return Context.XchangeRates.FirstOrDefault(x => x.Id.Equals(id));
        }

        public void Delete(Guid id)
        {
            var removedItem = Context.XchangeRates.FirstOrDefault(x => x.Id.Equals(id));
            if(removedItem == null)
                throw new EntityNotFoundException("XchangeRate");
            Context.XchangeRates.Remove(removedItem);
            Context.SaveChanges();
        }

        public void Delete(XchangeRateModel item)
        {
            Context.XchangeRates.Remove(item);
            Context.SaveChanges();
        }

        public IEnumerable<XchangeRateModel> GetAll()
        {
            return Context.XchangeRates;
        }

        public IEnumerable<IXchangeRate> GetData(IKeySupportedCriteria criteria, IXchangeRateFilter filter)
        {

            if (filter == null)
                throw new ArgumentNullException("filter");
            if (criteria == null)
                throw new ArgumentNullException("criteria");
            
            var source = from rate in Context.XchangeRates
                         where criteria.Identificators.Contains(rate.Pair.PairId)
                         select rate;
            
            RepositoryMappingHelper.ResetMapping();
            RepositoryMappingHelper.CreateXChangeRateMapping();

            var result = Mapper.Map<IEnumerable<XchangeRateModel>, IEnumerable<IXchangeRate>>(source);
            return filter.Filtrate(result) as IEnumerable<IXchangeRate>;
        }
    }
}
